<template>
  <div class="flex w-full h-screen overflow-hidden">
    <div class="h-full" style="width: 150px;">
      <div class=" flex flex-col justify-center h-full w-full items-center gap-4">
        <div>
          <div class="text-blue-600">
            <span class="text-blue-600">每秒帧数:</span> {{ frame }}
          </div>
        </div>
        <div>
          <button type="button" @click="uploadImage"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            打开相册
          </button>
        </div>
        <div>
          <button type="button"
                  @click="captureImage"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            连接无人机
          </button>
        </div>
        <div>
          <button type="button" @click="getCloudData"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            云端数据
          </button>
        </div>
        <div>
        </div>
      </div>
    </div>
    <div class="flex-1 bg-slate-50 rounded-2xl shadow-lg">
      <router-view />
    </div>
    <div style="width: 150px;" class="h-full">
      <div class=" flex flex-col justify-center h-full w-full items-center gap-4">
        <div>
          <div class="text-blue-600">
            <span>推理速度:</span> {{ speed }}
          </div>
        </div>
        <div>
          <button type="button" @click="predictImage"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            开始预测
          </button>
        </div>
        <div>
          <button type="button" @click="saveImage"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            保存结果
          </button>
        </div>
        <div>
          <button type="button" @click="dialogModal = true"
            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
            上传云端
          </button>
        </div>
        <div>
        </div>
      </div>
    </div>
    <q-dialog v-model="dialogModal" :full-width="true">
      <q-card>
        <q-card-section>
          <div class="text-h6 text-blue-600">上传云端</div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <img style="width: 300px;height: 200px; margin: auto;" :src="pic_url">
          <div class="text-blue-600 ">
            <span>
              稻穗计数：{{ count }}
            </span>
          </div>
          <div>
            <q-input v-model="pic_name" label="图片名称" />
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="确认" @click="uploadCloud" class="text-blue-500" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="showAllModal" :full-width="true" transition-show="slide-up" transition-hide="slide-down">
      <q-card v-if="rows.length > 0">
        <q-card-section class="q-pt-none">
          <q-table dense title="云端数据" :rows="rows" :columns="columns">
            <template v-slot:body-cell-url="props">
              <q-td :props="props">
                <img :src="props.row.url" style="width: 50px;height: 50px;">
              </q-td>
            </template>

          </q-table>
        </q-card-section>
      </q-card>
    </q-dialog>



  </div>

</template>

<script setup>
import {ref} from 'vue';
import {api} from 'src/boot/axios';
import bus from 'src/utils/bus';
import {useQuasar} from 'quasar'
import {Camera, CameraResultType} from '@capacitor/camera'

const dialogModal = ref(false)
const $q = useQuasar()
const columns = [
  {
    name: 'name',
    required: true,
    label: '图片名称',
    align: 'left',
    field: 'name',
    sortable: true
  },
  {
    name: 'url',
    required: true,
    label: '图片地址',
    align: 'left',
    field: 'url',
    sortable: true
  },
  {
    name: 'num',
    required: true,
    label: '稻穗数量',
    align: 'left',
    field: 'num',
    sortable: true
  }
]
const rows = ref([])

const frame = ref(0)
const speed = ref(0)
const pic = ref(null)
const pic_url = ref('')
const count = ref(0)
const pic_name = ref('')
const showAllModal = ref(false)
const shotImage = ref(null)
const iou = ref(null)
const trust = ref(null)

async function captureImage () {
  console.log('captureImage')
  const image = await Camera.getPhoto({
    quality: 90,
    allowEditing: true,
    resultType: CameraResultType.Uri
  })

  // The result will vary on the value of the resultType option.
  // CameraResultType.Uri - Get the result from image.webPath
  // CameraResultType.Base64 - Get the result from image.base64String
  // CameraResultType.DataUrl - Get the result from image.dataUrl
  let blob = await fetch(image.webPath).then(r => r.blob());
  let file = new File([blob], 'image.jpg', {type: 'image/jpeg'});
  pic.value = file;
  document.getElementById('main-img').src = image.webPath
  shotImage.value = image.webPath
}
const uploadImage = () => {
  let input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = (e) => {
    let file = e.target.files[0];
    pic.value = e.target.files[0];
    let reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onload = (e) => {
      let img = document.getElementById('main-img');
      img.src = e.target.result;

    }
  }
  input.click();
}
const predictImage = () => {
  bus.emit('predict', pic.value)
}


bus.on('revceive_predict', (data) => {
  let img = document.getElementById('main-img');
  console.log(data);
  img.src = data.url;
  pic_url.value = data.url;
  count.value = data.num;
  speed.value = Math.round(data.inference * 100) / 100;
  frame.value = Math.round(data.fps * 1000 * 100) / 100;
})

function downloadFile(url, fileName) {
  const x = new XMLHttpRequest()
  x.open("GET", url, true)
  x.responseType = 'blob'
  x.onload=function(e) {
    console.log(x.response)
    const url = window.URL.createObjectURL(x.response)
    console.log(url)
    const a = document.createElement('a')
    a.href = url
    a.target = '_blank'
    a.download = fileName
    a.click()
    a.remove()
    $q.notify({
      message: '下载成功',
      color: 'green',
      position: 'top'
    })
  }
  x.send()
}
const saveImage = () => {
  let dom = document.getElementById('main-img');
  let url = dom.src;
  downloadFile(url, 'result.jpg')
}
const uploadCloud = () => {
  let payload = {
    name: pic_name.value,
    url: pic_url.value,
    num: count.value
  }
  api.post('/upload_data_to_cloud', payload).then(res => {
    if (res.data.code === 200) {
      $q.notify({
        message: '上传成功',
        color: 'green',
        position: 'top'
      })
    } else {
      $q.notify({
        message: '上传失败',
        color: 'red',
        position: 'top'
      })
    }
  })
}
const getCloudData = () => {
  api.get('/get_data_from_cloud').then(res => {
    if (res.data.code === 200) {
      showAllModal.value = true;
      rows.value = res.data.data;
      if (res.data.data.length === 0) {
        $q.notify({
          message: '云端数据为空',
          position: 'top',
          type: 'info'
        })
        showAllModal.value = false;
      }

    } else {
      $q.notify({
        message: '获取云端数据失败',
        color: 'red',
        position: 'top'
      })
    }
  }).catch(err=>{
    alert(err)
  })
}
</script>
